package br.com.loja.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @brief Classe DBCreator
 * @author David Luiz
 * @date 20/11/2014
 */
public class DBCreator {

    private static Connection con;

    public DBCreator() {

    }

    public static boolean createDB(String url, String user, String pwd) {

        String strUrl[], db;
        strUrl = url.split("/");
        int i = strUrl.length - 1;
        db = strUrl[i];

        try {
            con = DriverManager.getConnection(url, user, pwd);
        } catch (SQLException e1) {
            createDB(url, db, user, pwd);
        }

        return (con != null);
    }

    private static void createDB(String url, String db, String user, String pwd) {
        try {
            String urlReplace = url.replaceAll(db, "");
            con = DriverManager.getConnection(urlReplace, user, pwd);
            Statement createStatement = con.createStatement();
            createStatement.executeUpdate("CREATE DATABASE " + db);
        } catch (SQLException e) {
            System.err.println("Falha ao tentar criar banco de dados\n" + e.getMessage());
            e.printStackTrace();
        }
    }

}
